﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace RouterControl.WhsAddIn
{
	public sealed class UserRecognizeWait : IDisposable
	{
		private DateTime _start = DateTime.Now;
        private Thread _dialogThread;
        private SimpleUserWaitDialog _dialog;
        private string _title;

        public UserRecognizeWait(bool showWaitDialog, string title)
        {
            _title = title;

            // show dialog?
            if (showWaitDialog)
            {
                _dialogThread = new Thread(
                    new ThreadStart(DialogThreadStart)
                    );

                _dialogThread.IsBackground = true;

                _dialogThread.Start();
            }
        }

        public UserRecognizeWait(bool showWaitDialog)
            : this(showWaitDialog, null)
        {
        }

        private void DialogThreadStart()
        {
            if (string.IsNullOrEmpty(_title))
            {
                _dialog = new SimpleUserWaitDialog(
                    Properties.Resources.txtDefaultWaitDialogTitle
                    );
            }
            else
            {
                _dialog = new SimpleUserWaitDialog(
                    _title
                    );
            }

            _dialog.ShowDialog();
        }

		public void Dispose()
		{
			var minTime = Properties.Settings.Default.MinUserRecognizeSeconds;
			var diffTime = (DateTime.Now - _start);

			if (minTime > diffTime)
				System.Threading.Thread.Sleep(minTime - diffTime);

            // close dialog
            if (_dialog != null)
            {
                _dialog.Close();
                _dialogThread.Join();
                _dialog.Dispose();
            }
		}
	}
}
